<template>
	<view>
		<yy-paging v-model="dataList" @query="queryList"
			:style="{ backgroundImage: `url(${vk.myfn.handleImageUrl(location?.lives?.[0]?.home || '')})` }" ref="paging"
			class="backgroundImage" :auto="false" @scroll="scroll" :refresher-enabled="true">
			<template #empty>
				<yy-empty></yy-empty>
			</template>
			<template #loadingMoreNoMore>
				<yy-nomore></yy-nomore>
			</template>
			<template #top>
				<u-navbar back-text="返回" :is-back="false" height="44" :border-bottom="false"
					:background="{ backgroundColor: isScroll ? 'transparent' : 'transparent' }">
					<view class="flex gap-2 justify-between items-center px-3 w-full">
						<view class="flex gap-1 items-center" @click="openMapSelection">
							<image src="/static/dddr48.png" class="size-[1rem] flex-none" mode="aspectFill" />
							<!-- <view class="text-[.75rem] text-[#161A24] font-bold line-clamp-1" v-if="vk.myfn.isIOS()">
                {{ vk.getVuex('$user.positioning').address || obtainLocation }}
              </view> -->
							<!-- {{ vk.getVuex('$user.positioning').address }} -->
							<!-- {{ vk.getVuex('$app.checkLocationPermission.isOpen') }} -->
							<view class="text-[.75rem] text-[#161A24] font-bold line-clamp-1">
								<!-- {{ location?.lives?.[0]?.city + location?.lives?.[0]?.district || obtainLocation }} -->
								{{
                  vk.getVuex('$user.positioning').address ||
                  (vk.getVuex('$app.checkLocationPermission.isOpen') ? '获取定位中...' : '定位获取失败')
                }}
							</view>
							<image src="/static/dddr40.png" class="size-[1rem] flex-none" mode="aspectFill" />
						</view>

						<view class="flex flex-none gap-1 items-center">
							<view v-if="!vk.pubfn.isNull(location)" class="flex items-center"
								@click="openWeather(location?.lives?.[0]?.adcode)">
								<view class="text-[.625rem] text-[#161A24] ml-2 flex-none">
									{{ location?.lives?.[0]?.district || '未知区域' }}
								</view>
								<view class="flex-none px-1">
									<view class="h-[.5rem] border-l border-solid border-[#C0C4CC]"></view>
								</view>
								<view class="text-[.625rem] text-[#161A24] flex-none">
									{{ location?.lives?.[0]?.weather || '未知天气' }}/ {{ location?.lives?.[0]?.temperature || '--' }}°
								</view>
							</view>
							<view class="size-5" @click="vk.myfn.shareWithSystem()">
								<image src="/static/dddr35.png" class="!size-full" mode="aspectFill" />
							</view>
						</view>
					</view>
				</u-navbar>

				<!-- 搜索 -->
				<view class="p-4 pt-0">
					<view class="w-full h-[2.25rem] bg-[#FFFFFF] rounded-[.5rem] flex items-center gap-3 px-4"
						@click="vk.navigateTo('/pages/index/searchFor')">
						<image src="/static/dddr59.png" class="size-4" mode="aspectFill" />
						<view class="h-[.625rem] border-l border-solid border-[#C0C4CC]"> </view>
						<view class="text-[.8125rem] text-[#8E9299]">搜索想找的鱼种、钓点名、用户名等</view>
					</view>
				</view>
			</template>
			<view class="flex flex-col gap-4 p-4 pt-0">
				<!-- 轮播图 -->
				<u-swiper :list="swiperList" height="164" borderRadius="16" @click="openDetails"></u-swiper>
				<view class="flex gap-6 items-center">
					<view v-for="(i, k) in list" class="flex flex-col gap-1 justify-start items-center" :key="k"
						@click="switchCategories(k)">
						<text class="text-[#0d111a]" :class="current === k ? 'font-medium text-[1.125rem]' : 'text-[1rem]'">
							{{ i }}
						</text>
						<image src="/static/dddr74.png" v-if="current === k" class="w-[1.125rem] h-[.25rem]" mode="aspectFill" />
						<view v-else class="w-[1.125rem] h-[.25rem]"></view>
					</view>
				</view>
				<view class="grid grid-cols-4 gap-2">
					<view class="col-span-1 bg-white rounded-[1.125rem] h-[1.75rem] flex justify-center items-center"
						v-for="(i, k) in list2" @click="switchToList2(k)" :key="k">
						<text class="text-[.75rem]" :class="current2 == k ? 'text-[#000] font-bold' : 'text-[#5C6068] '">
							{{ i }}
						</text>
					</view>
				</view>

				<view class="bg-[#FFFFFF] rounded-[.5rem] flex items-center p-3 justify-between"
					v-if="!vk.getVuex('$app.checkLocationPermission.isOpen')">
					<view class="text-[.8125rem] text-[#171B24]"> 未开启定位，为你推荐以下钓点 </view>
					<view @click="vk.myfn.openLocationSettings()"
						class="w-[4.5rem] h-[1.5rem] bg-[#00A9AB] font-medium rounded-full flex items-center justify-center">
						<view class="text-[.75rem] text-[#FFFFFF]"> 开启定位 </view>
					</view>
				</view>

				<view v-for="(i, k) in dataList" :key="k" class="flex gap-2 bg-white p-4 pb-2 rounded-[.75rem] flex-col"
					@click="jumpDetails(i)" @touchstart="handleTouchStart(i.id, $event)" @touchend="handleTouchEnd($event)"
					@touchmove="handleTouchMove($event)">
					<view class="flex gap-2 items-start">
						<view class="w-[5.5rem] flex-none relative h-[7.3125rem]">
							<u-image :src="i.thumb" mode="aspectFill" class="!size-full" borderRadius=".5rem" />
							<image v-if="i.is_paid_spot == 1 && i.is_paid == 0" src="/static/dddr87.png"
								class="h-[1.0625rem] absolute -left-[.125rem] top-0" mode="heightFix" />
							<image v-if="i.is_paid_spot == 1 && i.is_paid == 1" src="/static/dddr86.png"
								class="h-[1.0625rem] absolute -left-[.125rem] top-0" mode="heightFix" />
							<view class="size-full flex absolute inset-0 flex-col flex-grow justify-between p-1">
								<view></view>
								<view class="flex justify-between items-center">
									<view v-for="(img, imgIndex) in i?.images.slice(0, 3)" :key="imgIndex" class="relative"
										:class="imgIndex > 0 ? '-ml-3' : ''">
										<view class="size-[1.5rem] rounded-[.3125rem] border relative z-[1] overflow-hidden"
											:style="`z-index: ${3 - imgIndex};`">
											<u-image :src="img" class="!size-full" mode="aspectFill" />
										</view>
									</view>
									<view class="text-[.875rem] text-transparent ml-1">+{{ i?.images.length }}</view>
								</view>
							</view>
						</view>
						<view class="flex flex-col justify-between w-full h-full min-h-[7.3125rem]">
							<view class="flex gap-1 justify-between items-start w-full">
								<view class="text-[1rem] text-[#161A24] font-bold line-clamp-1">
									{{ i.name }}
								</view>
								<view
									class="rounded-full bg-[#F2F5F7] text-[.625rem] text-[#5C6068] font-bold px-[.4375rem] py-[.1875rem]"
									v-if="i.distance">
									{{ i.distance }}
								</view>
							</view>
							<view class="text-[.8125rem] text-[#5C6068] line-clamp-2"> {{ i.description }} </view>

							<view class="flex flex-wrap gap-1 items-center">
								<view v-for="(i, k) in i?.ext?.fish_species || []" :key="k"
									class="px-[.375rem] py-[.0625rem] bg-[#F2F5F7] rounded-[.25rem] whitespace-nowrap">
									<view class="text-[.625rem] text-[#5C6068]"> {{ i.name }} </view>
								</view>
							</view>
							<view class="flex justify-between items-center">
								<view class="flex items-center text-[.6875rem] text-[#5C6068] gap-1">
									<view class="flex items-center">
										<image :src="vk.myfn.handleImageUrl(i.weather?.lives?.[0]?.item)" mode="aspectFill"
											class="!size-[.875rem]" />
										<text class="ml-[.125rem]">{{ i.weather?.lives?.[0]?.weather || '未知天气' }}</text>
									</view>
									<text class="h-[.5rem] border-l border-solid border-[#C1C4C9]"></text>
									<text>{{ i.weather.lives[0].temperature }}°C</text>
									<text class="h-[.5rem] border-l border-solid border-[#C1C4C9]"></text>
									<text>{{ i.weather?.lives[0]?.district || '未知区域' }}</text>
								</view>
								<view class="flex relative justify-end">
									<view
										class="bg-gradient-to-r from-[#FFBF3A]/30 to-white h-[.375rem] w-[115%] absolute rounded-[.1875rem] bottom-1 z-20">
									</view>
									<view class="flex relative z-20 items-baseline gap-[0.0625rem]">
										<text class="font-[oxanium] text-[1.125rem] text-[#002021] font-bold">{{
                      (i.score || 0).toFixed(1)
                    }}</text>
										<text class="text-[.625rem] text-[#002021]">分</text>
									</view>
								</view>
							</view>
						</view>
					</view>
					<u-line />

					<!-- 免费 -->
					<view class="flex justify-between items-center" @click.stop="goHere(i)" v-if="!i?.is_paid_spot || i?.is_paid">
						<view class="flex gap-1 items-center">
							<image src="/static/dddr17.png" class="size-4" mode="aspectFill" />
							<view class="text-[.6875rem] text-[#5C6068] line-clamp-1">{{ i.location_name }}</view>
						</view>
						<image src="/static/dddr47.png" class="size-7" mode="aspectFill" />
					</view>
					<!-- 付费  is_paid  是否支付     is_paid_spot  需要付费  -->

					<view class="flex justify-between items-center" v-if="i.is_paid_spot && !i.is_paid" @click.stop="buyNow(i)">
						<view class="flex gap-1 items-center">
							<view class="flex items-center">
								<view
									class="size-5 flex overflow-hidden justify-center items-center -ml-2 bg-gray-200 rounded-full border"
									:style="`z-index: ${5 - k};`" v-for="(i, k) in i?.purchased_users.slice(0, 3)" :key="k">
									<image :src="i.avatar ? vk.myfn.handleImageUrl(i.avatar) : '/static/dddr103.png'" class="size-full"
										mode="aspectFill" />
								</view>
							</view>
							<text class="text-[.6875rem] text-[#00A9AB]" v-if="i?.sold_count">
								{{ i?.sold_count }}人已解锁该钓点
							</text>
							<view class="flex gap-1 items-center" v-else>
								<image src="/static/dddr131.png" mode="aspectFill" class="size-4" />
								<view class="text-[.6875rem] text-[#00A9AB]">解锁此钓点查看视频指路</view>
							</view>
						</view>

						<yy-amountBtn :paid_amount="i.paid_amount"></yy-amountBtn>
					</view>
				</view>
			</view>

			<template #bottom>
				<view class="pb-env bg-[#fff]">
					<yy-tabbar :tabbarIndex="tabbarIndex"></yy-tabbar>
				</view>
			</template>
		</yy-paging>
		<yy-buy v-model="modelValue" :modelValueData="modelValueData" @update:modelValue="modelValue = $event"
			@paySuccess="paySuccess"></yy-buy>
		<yy-noNetwork v-if="!vk.getVuex('$app.networkType')"></yy-noNetwork>
		<!-- 审核中 -->
		<yy-reviewFailed :show="showReviewFailed" @update:show="showReviewFailed = $event"></yy-reviewFailed>
		<!-- 审核失败 -->
		<yy-auditFailed :show="showAuditFailed" @update:show="showAuditFailed = $event" @resubmit="resubmit">
		</yy-auditFailed>

		<u-action-sheet :list="sheetList" v-model="sheetShow" @click="selectSheet"></u-action-sheet>
		<yy-alert ref="alert" @alertConfirm="alertConfirm"></yy-alert>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabbarIndex: 1, // 底部导航栏索引
				isScroll: false, // 是否滚动
				isSticky: false, // 是否吸顶
				dataList: [], // 列表数据
				automatic: false, // 是否自动加载
				basanList: {}, // 钓点列表数据
				list: ['手杆', '路亚'], // 钓鱼方式分类
				list2: ['全部', '付费', '免费', '附近'], // 筛选分类
				current2: 0, // 当前选中的筛选分类索引
				current: 0, // 当前选中的钓鱼方式索引
				tags: [], // 标签数据
				location: {}, // 定位信息
				swiperList: [], // 轮播图列表
				lat: '', // 纬度
				lng: '', // 经度
				modelValue: false, // 购买弹窗显示状态
				modelValueData: {}, // 购买弹窗数据
				sheetShow: false, // 操作菜单显示状态
				sheetList: [{
						text: '举报' // 举报选项
					},
					{
						text: '不敢兴趣' // 不感兴趣选项
					}
				],
				touchStartTime: 0, // 触摸开始时间
				touchStartId: null, // 触摸开始时的ID
				hasMoved: false, // 是否发生移动
				longPressTimer: null, // 长按定时器
				sheetShow: false, // 操作菜单显示状态
				showReviewFailed: false, // 审核中状态显示
				showAuditFailed: false // 审核失败状态显示
			}
		},
		// onPageScroll({ scrollTop }) {
		//   this.isScroll = scrollTop > 0
		//   this.isSticky = scrollTop > 170
		// },

		onUnload() {
			// 页面隐藏时清除监听器
			uni.$off('returnUpdatedData')
		},
		onShow() {
			// vk.navigateTo('/pages/index/66')
			uni.hideTabBar()

			uni.$once('returnUpdatedData', res => {
				// 判断res是否只有一个字段,如果是则不更新数据
				const index = this.dataList.findIndex(item => item.id === Number(res.id))
				if (Object.keys(res).length > 1) {
					this.$set(this.dataList, index, res)
				} else {
					this.dataList.splice(index, 1)
				}
			})
			// 获取权限
			// let checkLocationPermission = vk.myfn.checkLocationPermission()
			// vk.setVuex('$app.checkLocationPermission', checkLocationPermission)
			// this.obtainLocation = vk.getVuex('$app.checkLocationPermission') ? '获取定位中...' : '定位失败'
		},
		onNavigationBarButtonTap(e) {
			console.log('e==> ', e)
		},
		watch: {
			'$store.state.$app.homePageUpdate': {
				// immediate: true,
				deep: true,
				handler(newValue, oldValue) {
					console.log('newValuenewValuenewValuenewValuenewValuenewValue==> ', newValue)
					this.basanIndex()
					this.$refs.paging.reload()
					// if (!newValue) vk.myfn.getLocation()
				}
			}
		},

		onLoad() {
			setTimeout(() => {
				this.basanIndex()
				this.$refs.paging.refresh()
			}, 0)
		},

		methods: {
			alertConfirm() {
				vk.myfn.openLocationSettings()
			},
			openWeather(adcode) {
				vk.navigateTo(`/pages/index/7DayWeather?adcode=${adcode}`)
			},
			resubmit() {
				vk.navigateTo({
					url: '/pages/my/settled'
				})
			},
			async openDetails(e) {
				///pages/my/settled
				let url = this.swiperList[e].link_url
				if (!url) return
				if (url == '/pages/my/settled') {
					let res = await api.joinDarenStatus()
					let entryStatus = res.data.status
					// -1=未申请,0=待审核,1=通过,2=拒绝
					const STATUS_MAP = {
						'-1': () =>
							vk.navigateTo({
								url: '/pages/my/settled'
							}),
						0: () => (this.showReviewFailed = true),
						1: () =>
							vk.navigateTo({
								url: '/pages/my/successfullySettledIn'
							}),
						2: () => (this.showAuditFailed = true)
					}
					const handler = STATUS_MAP[entryStatus]
					if (handler) {
						handler()
					}
					return
				}

				vk.navigateTo(this.swiperList[e].link_url)
			},
			reconnects() {
				vk.showLoading('加载中...')
				// this.getCurrentLocation()
				this.basanIndex()
			},
			paySuccess() {
				this.$refs.paging.refresh()
			},
			async selectSheet(e) {
				if (e === 0) {
					vk.navigateTo(`/pages/my/report?id=${this.touchStartId}&type=1`)
					return
				}
				if (e === 1) {
					await api.notInterest({
						basan_id: this.touchStartId
					})
					vk.toast('操作成功，已减少此类内容推荐', 500, () => {
						this.$refs.paging.refresh()
					})
				}
			},
			handleTouchStart(id, event) {
				this.touchStartTime = Date.now()
				this.touchStartId = id
				this.hasMoved = false
				this.longPressTimer = setTimeout(() => {
					if (!this.hasMoved) {
						this.longpress(id)
					}
				}, 500) // 500ms 长按时间
			},

			handleTouchMove(event) {
				this.hasMoved = true
				if (this.longPressTimer) {
					clearTimeout(this.longPressTimer)
					this.longPressTimer = null
				}
			},

			handleTouchEnd(event) {
				if (this.longPressTimer) {
					clearTimeout(this.longPressTimer)
					this.longPressTimer = null
				}
			},
			longpress(id) {
				this.sheetShow = true
			},
			buyNow(i) {
				if (vk.myfn.isLogin()) {
					this.modelValue = true
					this.modelValueData = i
				}
			},
			async goHere(i) {
				const {
					lat,
					lng,
					address
				} = i
				vk.myfn.openMap(lat, lng, address)
			},

			switchToList2(k) {
				if (k == 3 && !vk.getVuex('$app.checkLocationPermission.isOpen')) {
					this.$refs.alert.config({
						show: true,
						title: '开启定位',
						describe: '定位权限未开启，是否前往设置开启定位',
						cancel: '取消',
						cancelColor: '#5C6068',
						confirm: '前往开启',
						confirmColor: '#00A9AB',
						eventType: 'openLocation'
					})
					return
				}
				this.current2 = k
				vk.showLoading('加载中...')
				this.$refs.paging.refresh()
			},
			scroll() {},

			// 打开地图选择定位
			async openMapSelection() {
				if (!vk.getVuex('$app.checkLocationPermission.isOpen')) {
					this.$refs.alert.config({
						show: true,
						title: '开启定位',
						describe: '定位权限未开启，是否前往设置开启定位',
						cancel: '取消',
						cancelColor: '#5C6068',
						confirm: '前往开启',
						confirmColor: '#00A9AB',
						eventType: 'openLocation'
					})
					return
				}

				let res = await vk.myfn.chooseLocation()
				console.log('打开地图获取定位==> ', res)
				vk.setVuex('$user.positioning', {
					lat: res.latitude,
					lng: res.longitude,
					address: res.name === '地图位置' ? res.address : res.name
				})
				this.basanIndex()
				this.$refs.paging.reload()
			},

			// 去详情
			jumpDetails(i) {
				vk.navigateTo({
					url: `/pages/index/details?id=${i.id}`
				})
			},
			// 获取轮播图
			async basanIndex() {
				let res = await api.basanIndex({
					lat: vk.getVuex('$user.positioning.lat'), //|| '30.572815', // 随机成都市经度
					lng: vk.getVuex('$user.positioning.lng') //|| '104.066801' // 随机成都市纬度
				})
				this.swiperList = res.data.banner.map(e => {
					e.image = vk.getConfig().imageUrl + e.image
					return e
				})
				this.basanList = res.data
				this.location = res.data.location || {}
				console.log(' this.location==> ', this.location)
			},
			//
			switchCategories(e) {
				this.current = e
				vk.showLoading('加载中...')
				this.$refs.paging.reload()
			},
			// 获取列表
			async queryList(page, limit) {
				let params = {
					lat: vk.getVuex('$user.positioning.lat'), //|| '30.572815', // 随机成都市经度
					lng: vk.getVuex('$user.positioning.lng'), //|| '104.066801' // 随机成都市纬度
					page,
					limit,
					basan_type: this.current + 1, // 手杆=1, 路亚=2
					not_user_ids: vk.getVuex('$user.userInfo').id || ''
				}

				// 根据current2添加对应参数
				switch (this.current2) {
					case 1: // 付费
						params.is_paid_spot = 1
						break
					case 2: // 免费
						params.is_paid_spot = 0
						break
					case 3: // 附近
						params.sort = 'distance'
						break
					default: // 全部
						break
				}
				let res = await api.getBasanList(params)
				this.$refs.paging.complete(res.data)

				// this.$refs.paging.setLocalPaging(res.data)
				vk.hideLoading()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.backgroundImage,
	page {
		background-repeat: no-repeat !important;
		background-size: 100% !important;
		background-position: top !important;
		// background-color: #f4f6f8 !important;
	}

	.bgg {
		background-image: url('/static/dddr64.png') !important;
		background-repeat: no-repeat !important;
		background-size: 100% !important;
		background-position: top !important;
	}
</style>